import hashlib
import random
from fastapi import APIRouter, Depends, HTTPException, Request, status, Body, Query, Path
from fastapi.responses import JSONResponse
from datetime import datetime, timedelta
from typing import List, Optional, Dict, Any
from pydantic import BaseModel, Field, validator
from uuid import UUID
import json
from sqlalchemy import select, and_, or_, func, update, delete
from sqlalchemy.ext.asyncio import AsyncSession
from passlib.context import CryptContext

from app.models.db import (
    SmsCode, get_async_session, User, Role, UserRole, 
    SystemConfig, OperationLog, UserSession, UserMsg, AnalysisDimension, ModelCallLog
)
from app.models.user import current_active_user, fastapi_users, get_user_manager
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
import string

router = APIRouter(prefix="/sysbase", tags=["系统管理"])

# Pydantic模型定义
class UserCreate(BaseModel):
    username: str
    email: Optional[str] = None
    password: str
    phone: str
    smscode: str  # 仍然需要验证码，但不会存储到用户表中
    nickname: Optional[str] = None
    department: Optional[str] = None
    position: Optional[str] = None
    
class UserUpdate(BaseModel):
    nickname: Optional[str] = None
    avatar: Optional[str] = None
    gender: Optional[int] = None
    birthday: Optional[datetime] = None
    department: Optional[str] = None
    position: Optional[str] = None
    status: Optional[int] = None
    
class RoleCreate(BaseModel):
    name: str
    description: Optional[str] = None
    
class RoleUpdate(BaseModel):
    name: Optional[str] = None
    description: Optional[str] = None
    permissions: Optional[List[str]] = None
    
class AssignRoleRequest(BaseModel):
    user_id: UUID
    role_id: str
    
class ConfigCreate(BaseModel):
    config_key: str
    config_value: str
    config_description: Optional[str] = None
    config_group: str = "system"
    
class ConfigUpdate(BaseModel):
    config_value: str
    config_description: Optional[str] = None
    config_group: Optional[str] = None

class OperationLogRecord(BaseModel):
    operation_type: str
    operation_content: str
    operation_result: int = 1
    operation_ip: Optional[str] = None

class ResetPasswordRequest(BaseModel):
    password: str
    confirmPassword: str
    
    @validator('confirmPassword')
    def passwords_match(cls, v, values, **kwargs):
        if 'password' in values and v != values['password']:
            raise ValueError('两次输入的密码不匹配')
        return v
    
    @validator('password')
    def password_valid(cls, v):
        if len(v) < 6:
            raise ValueError('密码长度不能少于6个字符')
        return v

async def record_operation_log(
    session: AsyncSession,
    user_id: Optional[UUID],
    operation_type: str,
    operation_content: str,
    operation_result: int = 1,
    operation_ip: Optional[str] = None
):
    """记录操作日志"""
    log = OperationLog(
        user_id=str(user_id) if user_id else None,
        operation_type=operation_type,
        operation_content=operation_content,
        operation_result=operation_result,
        operation_ip=operation_ip
    )
    session.add(log)
    await session.commit()

async def get_client_ip(request: Request) -> str:
    """获取客户端IP"""
    x_forwarded_for = request.headers.get("X-Forwarded-For")
    if x_forwarded_for:
        return x_forwarded_for.split(",")[0]
    return request.client.host

@router.post("/verify-sms-code")
async def verify_sms_code(
    phone: str,
    code: str,
    session: AsyncSession = Depends(get_async_session)
):
    """验证短信验证码"""
    # 查询验证码
    query = select(SmsCode).filter(
        SmsCode.phone == phone,
        SmsCode.code == code,
        SmsCode.expired_at > datetime.now()
    )
    result = await session.execute(query)
    sms_code = result.scalar_one_or_none()

    if not sms_code:
        raise HTTPException(status_code=400, detail="验证码无效或已过期")

    # 验证成功后删除验证码
    await session.delete(sms_code)
    await session.commit()

    return {"message": "验证码验证成功"}

@router.get("/captcha")
async def generate_captcha():
    # 生成随机字符串
    captcha_text = ''.join(random.choices(
        string.ascii_uppercase + string.digits, k=4))

    # 创建图片对象
    image = Image.new('RGB', (120, 40), color=(255, 255, 255))
    draw = ImageDraw.Draw(image)

    # 使用默认字体
    font = ImageFont.load_default()

    # 绘制验证码文本
    draw.text((10, 10), captcha_text, font=font, fill=(0, 0, 0))

    # 将图片保存到字节流中
    byte_io = BytesIO()
    image.save(byte_io, 'PNG')
    byte_io.seek(0)

    return {"captcha": captcha_text, "image": byte_io.getvalue()}

# =========== 用户管理API ===========
@router.get("/users", response_model=Dict[str, Any])
async def get_users(
    skip: int = Query(0, ge=0), 
    limit: int = Query(10, ge=1, le=100),
    keyword: Optional[str] = None,
    status: Optional[int] = None,
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(current_active_user)
):
    """获取用户列表"""
    query = select(User)
    
    # 添加过滤条件
    if keyword:
        query = query.filter(
            or_(
                User.email.ilike(f"%{keyword}%"),
                User.phone.ilike(f"%{keyword}%"),
                User.nickname.ilike(f"%{keyword}%"),
                User.department.ilike(f"%{keyword}%")
            )
        )
    
    if status is not None:
        query = query.filter(User.status == status)
    
    # 分页
    total_query = select(func.count()).select_from(query.subquery())
    total = await session.scalar(total_query)
    
    query = query.offset(skip).limit(limit).order_by(User.created_at.desc())
    result = await session.execute(query)
    users = result.scalars().all()
    
    return {
        "total": total,
        "items": [user.dict() for user in users]
    }

@router.get("/users/{user_id}", response_model=Dict[str, Any])
async def get_user(
    user_id: UUID,
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(current_active_user)
):
    """获取用户详情"""
    if not current_user.is_superuser and current_user.id != user_id:
        raise HTTPException(status_code=403, detail="权限不足")
    
    query = select(User).filter(User.id == user_id)
    result = await session.execute(query)
    user = result.scalars().first()
    
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 获取用户角色
    role_query = select(Role).join(
        UserRole, 
        and_(
            UserRole.role_id == Role.id,
            UserRole.user_id == str(user_id)
        )
    )
    result = await session.execute(role_query)
    roles = result.scalars().all()
    
    user_data = user.dict()
    user_data["roles"] = [role.dict() for role in roles]
    
    return user_data

@router.put("/users/{user_id}", response_model=Dict[str, Any])
async def update_user(
    user_id: UUID,
    user_data: UserUpdate,
    request: Request,
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(current_active_user)
):
    """更新用户信息"""
    # 检查权限
    if not current_user.is_superuser and current_user.id != user_id:
        raise HTTPException(status_code=403, detail="权限不足")
    
    # 只有超级管理员可以修改用户状态
    if user_data.status is not None and not current_user.is_superuser:
        raise HTTPException(status_code=403, detail="只有管理员可以修改用户状态")
    
    # 获取用户
    query = select(User).filter(User.id == user_id)
    result = await session.execute(query)
    user = result.scalars().first()
    
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 更新用户信息
    update_data = user_data.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(user, key, value)
    
    # 记录操作日志
    client_ip = await get_client_ip(request)
    await record_operation_log(
        session=session,
        user_id=current_user.id,
        operation_type="更新用户",
        operation_content=f"更新用户 {user.email} 的信息",
        operation_ip=client_ip
    )
    
    try:
        await session.commit()
    except Exception as e:
        await session.rollback()
        raise HTTPException(status_code=400, detail=str(e))
    
    return {"message": "用户信息更新成功", "user": user.dict()}

@router.delete("/users/{user_id}")
async def delete_user(
    user_id: str,
    request: Request,
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(current_active_user)
):
    """删除用户"""
    if not current_user.is_superuser:
        raise HTTPException(status_code=403, detail="权限不足")
    
    # 不能删除自己
    if current_user.id == user_id:
        raise HTTPException(status_code=400, detail="不能删除自己的账户")
    
    # 获取用户
    query = select(User).filter(User.id == user_id)
    result = await session.execute(query)
    user = result.scalars().first()
    
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 手动处理级联删除
    try:
        # 1. 先删除用户角色关联
        delete_user_roles = delete(UserRole).where(UserRole.user_id == str(user_id))
        await session.execute(delete_user_roles)
        
        # 2. 删除用户相关的操作日志
        delete_logs = delete(OperationLog).where(OperationLog.user_id == str(user_id))
        await session.execute(delete_logs)
        
        # 3. 删除用户的会话消息
        # 先获取所有会话ID
        session_query = select(UserSession.id).filter(UserSession.user_id == str(user_id))
        session_result = await session.execute(session_query)
        session_ids = [str(session_id[0]) for session_id in session_result.all()]
        
        # 删除会话相关的消息
        if session_ids:
            delete_msgs = delete(UserMsg).where(UserMsg.session_id.in_(session_ids))
            await session.execute(delete_msgs)
            
            # 4. 删除会话相关的分析维度
            delete_dimensions = delete(AnalysisDimension).where(AnalysisDimension.session_id.in_(session_ids))
            await session.execute(delete_dimensions)
            
            # 5. 删除用户会话
            delete_sessions = delete(UserSession).where(UserSession.user_id == str(user_id))
            await session.execute(delete_sessions)
        
        # 6. 最后删除用户
        await session.delete(user)
        
        # 记录操作日志
        client_ip = await get_client_ip(request)
        await record_operation_log(
            session=session,
            user_id=current_user.id,
            operation_type="删除用户",
            operation_content=f"删除用户 {user.email}",
            operation_ip=client_ip
        )
        
        await session.commit()
        return {"message": "用户删除成功"}
    except Exception as e:
        await session.rollback()
        raise HTTPException(status_code=400, detail=f"删除用户失败: {str(e)}")

# =========== 角色管理API ===========
@router.get("/roles", response_model=Dict[str, Any])
async def get_roles(
    skip: int = Query(0, ge=0), 
    limit: int = Query(10, ge=1, le=100),
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(current_active_user)
):
    """获取角色列表"""
    if not current_user.is_superuser:
        raise HTTPException(status_code=403, detail="权限不足")
    
    # 构建查询
    query = select(Role).order_by(Role.created_at)
    
    # 计算总数 - 使用子查询方式
    total_query = select(func.count()).select_from(query.subquery())
    total = await session.scalar(total_query)
    
    # 执行查询
    result = await session.execute(query.offset(skip).limit(limit))
    roles = result.scalars().all()
    
    # 查询每个角色关联的用户数量
    role_users_count = {}
    for role in roles:
        count_query = select(func.count()).select_from(UserRole).filter(UserRole.role_id == role.id)
        role_users_count[str(role.id)] = await session.scalar(count_query)
    
    role_list = []
    for role in roles:
        role_data = role.dict()
        role_data["user_count"] = role_users_count.get(str(role.id), 0)
        role_list.append(role_data)
    
    return {
        "total": total,
        "items": role_list
    }

@router.post("/roles", response_model=Dict[str, Any])
async def create_role(
    role_data: RoleCreate,
    request: Request,
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(current_active_user)
):
    """创建角色"""
    if not current_user.is_superuser:
        raise HTTPException(status_code=403, detail="权限不足")
    
    # 检查角色名是否已存在
    query = select(Role).filter(Role.name == role_data.name)
    result = await session.execute(query)
    existing_role = result.scalars().first()
    
    if existing_role:
        raise HTTPException(status_code=400, detail="角色名已存在")
    
    # 创建角色
    role = Role(
        name=role_data.name,
        description=role_data.description,
        is_system=0
    )
    
    session.add(role)
    
    # 记录操作日志
    client_ip = await get_client_ip(request)
    await record_operation_log(
        session=session,
        user_id=current_user.id,
        operation_type="创建角色",
        operation_content=f"创建角色 {role.name}",
        operation_ip=client_ip
    )
    
    try:
        await session.commit()
    except Exception as e:
        await session.rollback()
        raise HTTPException(status_code=400, detail=str(e))
    
    return {"message": "角色创建成功", "role": role.dict()}

@router.get("/roles/{role_id}", response_model=Dict[str, Any])
async def get_role(
    role_id: UUID,
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(current_active_user)
):
    """获取角色详情"""
    if not current_user.is_superuser:
        raise HTTPException(status_code=403, detail="权限不足")
    
    # 将UUID转换为字符串再查询
    query = select(Role).filter(Role.id == str(role_id))
    result = await session.execute(query)
    role = result.scalars().first()
    
    if not role:
        raise HTTPException(status_code=404, detail="角色不存在")
    
    # 获取角色关联的用户
    user_query = select(User).join(
        UserRole, 
        and_(
            UserRole.user_id == User.id,
            UserRole.role_id == str(role_id)
        )
    )
    result = await session.execute(user_query)
    users = result.scalars().all()
    
    role_data = role.dict()
    role_data["users"] = [{"id": str(user.id), "email": user.email, "nickname": user.nickname,"username":user.username } for user in users]
    
    return role_data

@router.put("/roles/{role_id}", response_model=Dict[str, Any])
async def update_role(
    role_id: str,
    role_data: RoleUpdate,
    request: Request,
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(current_active_user)
):
    """更新角色"""
    if not current_user.is_superuser:
        raise HTTPException(status_code=403, detail="权限不足")
    
    # 获取角色
    query = select(Role).filter(Role.id == role_id)
    result = await session.execute(query)
    role = result.scalars().first()
    
    if not role:
        raise HTTPException(status_code=404, detail="角色不存在")
    
    # 不能修改系统内置角色
    if role.is_system:
        raise HTTPException(status_code=400, detail="不能修改系统内置角色")
    
    # 检查角色名是否已存在
    if role_data.name and role_data.name != role.name:
        name_query = select(Role).filter(Role.name == role_data.name)
        name_result = await session.execute(name_query)
        existing_role = name_result.scalars().first()
        
        if existing_role:
            raise HTTPException(status_code=400, detail="角色名已存在")
    
    # 更新角色
    update_data = role_data.dict(exclude_unset=True)
    if "permissions" in update_data:
        update_data["permissions"] = json.dumps(update_data["permissions"])
    
    for key, value in update_data.items():
        setattr(role, key, value)
    
    # 记录操作日志
    client_ip = await get_client_ip(request)
    await record_operation_log(
        session=session,
        user_id=current_user.id,
        operation_type="更新角色",
        operation_content=f"更新角色 {role.name}",
        operation_ip=client_ip
    )
    
    try:
        await session.commit()
    except Exception as e:
        await session.rollback()
        raise HTTPException(status_code=400, detail=str(e))
    
    return {"message": "角色更新成功", "role": role.dict()}

@router.delete("/roles/{role_id}")
async def delete_role(
    role_id: UUID,
    request: Request,
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(current_active_user)
):
    """删除角色"""
    if not current_user.is_superuser:
        raise HTTPException(status_code=403, detail="权限不足")
    
    # 获取角色，将UUID转换为字符串
    query = select(Role).filter(Role.id == str(role_id))
    result = await session.execute(query)
    role = result.scalars().first()
    
    if not role:
        raise HTTPException(status_code=404, detail="角色不存在")
    
    # 不能删除系统内置角色
    if role.is_system:
        raise HTTPException(status_code=400, detail="不能删除系统内置角色")
    
    # 检查角色是否被用户使用
    user_count_query = select(func.count()).select_from(UserRole).filter(UserRole.role_id == str(role_id))
    user_count = await session.scalar(user_count_query)
    
    if user_count > 0:
        raise HTTPException(status_code=400, detail="该角色正在被用户使用，不能删除")
    
    try:
        # 手动处理级联删除
        # 1. 删除角色的用户关联记录
        delete_user_roles = delete(UserRole).where(UserRole.role_id == str(role_id))
        await session.execute(delete_user_roles)
        
        # 2. 删除角色
        await session.delete(role)
        
        # 记录操作日志
        client_ip = await get_client_ip(request)
        await record_operation_log(
            session=session,
            user_id=current_user.id,
            operation_type="删除角色",
            operation_content=f"删除角色 {role.name}",
            operation_ip=client_ip
        )
        
        await session.commit()
        return {"message": "角色删除成功"}
    except Exception as e:
        await session.rollback()
        raise HTTPException(status_code=400, detail=f"删除角色失败: {str(e)}")

@router.post("/users/{user_id}/roles")
async def assign_role_to_user(
    request: Request,
    user_id: str,
    role_data: Dict[str, str] = Body(...),
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(current_active_user)
):
    """为用户分配角色
    
    从请求体中获取role_id参数
    如果用户已有该角色，直接返回成功
    """
    role_id = role_data.get("role_id")
    if not role_id:
        raise HTTPException(status_code=400, detail="请提供role_id参数")
        
    if not current_user.is_superuser:
        raise HTTPException(status_code=403, detail="权限不足")
    
    # 检查用户是否存在
    user_query = select(User).filter(User.id == user_id)
    user_result = await session.execute(user_query)
    user = user_result.scalars().first()
    
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 检查角色是否存在，将UUID转换为字符串
    role_query = select(Role).filter(Role.id == role_id)
    role_result = await session.execute(role_query)
    role = role_result.scalars().first()
    
    if not role:
        raise HTTPException(status_code=404, detail="角色不存在")
    
    # 检查用户是否已经拥有该角色
    user_role_query = select(UserRole).filter(
        and_(
            UserRole.user_id == str(user_id),
            UserRole.role_id == str(role_id)
        )
    )
    user_role_result = await session.execute(user_role_query)
    existing_user_role = user_role_result.scalars().first()
    
    if existing_user_role:
        # 用户已有该角色，直接返回成功
        return {"message": "角色分配成功", "note": "用户已拥有该角色"}
    
    # 创建用户角色关联
    user_role = UserRole(
        user_id=str(user_id),
        role_id=str(role_id)
    )
    
    session.add(user_role)
    
    # 记录操作日志
    client_ip = await get_client_ip(request)
    await record_operation_log(
        session=session,
        user_id=current_user.id,
        operation_type="分配角色",
        operation_content=f"为用户 {user.email} 分配角色 {role.name}",
        operation_ip=client_ip
    )
    
    try:
        await session.commit()
    except Exception as e:
        await session.rollback()
        raise HTTPException(status_code=400, detail=str(e))
    
    return {"message": "角色分配成功"}

@router.delete("/users/{user_id}/roles/{role_id}")
async def remove_role_from_user(
    user_id: UUID,
    role_id: UUID,
    request: Request,
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(current_active_user)
):
    """从用户中移除角色"""
    if not current_user.is_superuser:
        raise HTTPException(status_code=403, detail="权限不足")
    
    # 检查用户是否存在
    user_query = select(User).filter(User.id == user_id)
    user_result = await session.execute(user_query)
    user = user_result.scalars().first()
    
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 检查角色是否存在，将UUID转换为字符串
    role_query = select(Role).filter(Role.id == str(role_id))
    role_result = await session.execute(role_query)
    role = role_result.scalars().first()
    
    if not role:
        raise HTTPException(status_code=404, detail="角色不存在")
    
    # 查询用户角色关联
    user_role_query = select(UserRole).filter(
        and_(
            UserRole.user_id == str(user_id),
            UserRole.role_id == str(role_id)
        )
    )
    user_role_result = await session.execute(user_role_query)
    user_role = user_role_result.scalars().first()
    
    if not user_role:
        raise HTTPException(status_code=404, detail="用户未分配该角色")
    
    # 删除用户角色关联
    await session.delete(user_role)
    
    # 记录操作日志
    client_ip = await get_client_ip(request)
    await record_operation_log(
        session=session,
        user_id=current_user.id,
        operation_type="移除角色",
        operation_content=f"从用户 {user.email} 中移除角色 {role.name}",
        operation_ip=client_ip
    )
    
    try:
        await session.commit()
    except Exception as e:
        await session.rollback()
        raise HTTPException(status_code=400, detail=str(e))
    
    return {"message": "角色移除成功"}

# =========== 系统配置API ===========
@router.get("/configs", response_model=List[Dict[str, Any]])
async def get_configs(
    group: Optional[str] = None,
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(current_active_user)
):
    """获取系统配置列表"""
    if not current_user.is_superuser:
        raise HTTPException(status_code=403, detail="权限不足")
    
    # 构建查询
    query = select(SystemConfig)
    
    if group:
        query = query.filter(SystemConfig.config_group == group)
    
    # 执行查询
    result = await session.execute(query)
    configs = result.scalars().all()
    
    return [config.dict() for config in configs]

@router.post("/configs", response_model=Dict[str, Any])
async def create_config(
    config_data: ConfigCreate,
    request: Request,
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(current_active_user)
):
    """创建系统配置"""
    if not current_user.is_superuser:
        raise HTTPException(status_code=403, detail="权限不足")
    
    # 检查配置键是否已存在
    query = select(SystemConfig).filter(SystemConfig.config_key == config_data.config_key)
    result = await session.execute(query)
    existing_config = result.scalars().first()
    
    if existing_config:
        raise HTTPException(status_code=400, detail="配置键已存在")
    
    # 创建配置
    config = SystemConfig(
        config_key=config_data.config_key,
        config_value=config_data.config_value,
        config_description=config_data.config_description,
        config_group=config_data.config_group,
        is_system=0
    )
    
    session.add(config)
    
    # 记录操作日志
    client_ip = await get_client_ip(request)
    await record_operation_log(
        session=session,
        user_id=current_user.id,
        operation_type="创建系统配置",
        operation_content=f"创建系统配置 {config.config_key}",
        operation_ip=client_ip
    )
    
    try:
        await session.commit()
    except Exception as e:
        await session.rollback()
        raise HTTPException(status_code=400, detail=str(e))
    
    return {"message": "系统配置创建成功", "config": config.dict()}

@router.get("/configs/{config_id}", response_model=Dict[str, Any])
async def get_config(
    config_id: UUID,
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(current_active_user)
):
    """获取系统配置详情"""
    if not current_user.is_superuser:
        raise HTTPException(status_code=403, detail="权限不足")
    
    # 查询配置
    query = select(SystemConfig).filter(SystemConfig.id == config_id)
    result = await session.execute(query)
    config = result.scalars().first()
    
    if not config:
        raise HTTPException(status_code=404, detail="系统配置不存在")
    
    return config.dict()

@router.put("/configs/{config_id}", response_model=Dict[str, Any])
async def update_config(
    config_id: str,
    config_data: ConfigUpdate,
    request: Request,
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(current_active_user)
):
    """更新系统配置"""
    if not current_user.is_superuser:
        raise HTTPException(status_code=403, detail="权限不足")
    
    # 查询配置
    query = select(SystemConfig).filter(SystemConfig.id == config_id)
    result = await session.execute(query)
    config = result.scalars().first()
    
    if not config:
        raise HTTPException(status_code=404, detail="系统配置不存在")
    
    # 不能修改系统内置配置
    if config.is_system:
        raise HTTPException(status_code=400, detail="不能修改系统内置配置")
    
    # 更新配置
    update_data = config_data.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(config, key, value)
    
    # 记录操作日志
    client_ip = await get_client_ip(request)
    await record_operation_log(
        session=session,
        user_id=current_user.id,
        operation_type="更新系统配置",
        operation_content=f"更新系统配置 {config.config_key}",
        operation_ip=client_ip
    )
    
    try:
        await session.commit()
    except Exception as e:
        await session.rollback()
        raise HTTPException(status_code=400, detail=str(e))
    
    return {"message": "系统配置更新成功", "config": config.dict()}

@router.delete("/configs/{config_id}")
async def delete_config(
    config_id: str,
    request: Request,
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(current_active_user)
):
    """删除系统配置"""
    if not current_user.is_superuser:
        raise HTTPException(status_code=403, detail="权限不足")
    
    # 查询配置
    query = select(SystemConfig).filter(SystemConfig.id == config_id)
    result = await session.execute(query)
    config = result.scalars().first()
    
    if not config:
        raise HTTPException(status_code=404, detail="系统配置不存在")
    
    # 不能删除系统内置配置
    if config.is_system:
        raise HTTPException(status_code=400, detail="不能删除系统内置配置")
    
    # 删除配置
    await session.delete(config)
    
    # 记录操作日志
    client_ip = await get_client_ip(request)
    await record_operation_log(
        session=session,
        user_id=current_user.id,
        operation_type="删除系统配置",
        operation_content=f"删除系统配置 {config.config_key}",
        operation_ip=client_ip
    )
    
    try:
        await session.commit()
    except Exception as e:
        await session.rollback()
        raise HTTPException(status_code=400, detail=str(e))
    
    return {"message": "系统配置删除成功"}

# =========== 操作日志API ===========
@router.get("/operation-logs", response_model=Dict[str, Any])
async def get_operation_logs(
    skip: int = Query(0, ge=0),
    limit: int = Query(20, ge=1, le=100),
    user_id: Optional[str] = None,
    operation_type: Optional[str] = None,
    start_time: Optional[str] = None,
    end_time: Optional[str] = None,
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(current_active_user)
):
    """获取操作日志列表"""
    if not current_user.is_superuser:
        raise HTTPException(status_code=403, detail="权限不足")
    
    # 构建查询
    query = select(OperationLog)
    
    # 添加过滤条件
    if user_id:
        query = query.filter(OperationLog.user_id == str(user_id))
    
    if operation_type:
        query = query.filter(OperationLog.operation_type == operation_type)
    
    if start_time:
        query = query.filter(OperationLog.operation_time >= start_time)
    
    if end_time:
        query = query.filter(OperationLog.operation_time <= end_time)
    
    # 查询总数
    total_query = select(func.count()).select_from(query.subquery())
    total = await session.scalar(total_query)
    
    # 分页查询
    query = query.order_by(OperationLog.operation_time.desc()).offset(skip).limit(limit)
    result = await session.execute(query)
    logs = result.scalars().all()
    
    # 查询关联的用户信息
    log_list = []
    for log in logs:
        log_data = log.dict()
        
        if log.user_id:
            user_query = select(User).filter(User.id == log.user_id)
            user_result = await session.execute(user_query)
            user = user_result.scalars().first()
            
            if user:
                log_data["user_email"] = user.email
                log_data["user_nickname"] = user.nickname
        
        log_list.append(log_data)
    
    return {
        "total": total,
        "items": log_list
    }

@router.get("/my-profile", response_model=Dict[str, Any])
async def get_my_profile(
    current_user: User = Depends(current_active_user)
):
    """获取当前用户的个人资料"""
    return current_user.dict()

@router.post("/users/{user_id}/reset-password")
async def reset_user_password(
    request: Request,
    user_id: str,
    password_data: ResetPasswordRequest,
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(current_active_user)
):
    """管理员重置用户密码
    
    只有超级管理员可以重置用户密码
    需要提供新密码和确认密码（两者必须相同）
    """
    # 验证当前用户是否为超级管理员
    if not current_user.is_superuser:
        raise HTTPException(status_code=403, detail="权限不足，只有超级管理员可以重置密码")
    
    # 检查用户是否存在
    user_query = select(User).filter(User.id == user_id)
    user_result = await session.execute(user_query)
    user = user_result.scalars().first()
    
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 创建密码哈希
    pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
    password_hash = pwd_context.hash(password_data.password)
    
    # 更新用户密码
    user.hashed_password = password_hash
    
    # 记录操作日志
    client_ip = await get_client_ip(request)
    await record_operation_log(
        session=session,
        user_id=current_user.id,
        operation_type="重置密码",
        operation_content=f"管理员重置了用户 {user.email} 的密码",
        operation_ip=client_ip
    )
    
    try:
        await session.commit()
    except Exception as e:
        await session.rollback()
        raise HTTPException(status_code=400, detail=f"重置密码失败: {str(e)}")
    
    return {"message": "用户密码重置成功"}

@router.post("/get_model_call_logs", response_model=None)
async def get_model_call_logs(
    page: int = Query(1, ge=1, description="页码，从1开始"),
    page_size: int = Query(10, ge=1, le=1000, description="每页记录数"),
    start_date: Optional[str] = Query(None, description="开始日期，格式：YYYY-MM-DD"),
    end_date: Optional[str] = Query(None, description="结束日期，格式：YYYY-MM-DD"),
    model_name: Optional[str] = Query(None, description="模型名称"),
    user_id: Optional[str] = Query(None, description="用户ID"),
    session: AsyncSession = Depends(get_async_session),
    current_user: User = Depends(current_active_user)
):
    """
    获取AI大模型调用记录数据
    
    参数:
        page: 页码，从1开始
        page_size: 每页记录数
        start_date: 开始日期，格式：YYYY-MM-DD
        end_date: 结束日期，格式：YYYY-MM-DD
        model_name: 模型名称
        user_id: 用户ID
        
    返回:
        dict: 包含记录列表、总记录数和分页信息
    """
    try:
        # 检查用户是否具有管理员权限
        if not current_user.is_superuser:
            raise HTTPException(status_code=403, detail="只有管理员可以访问此接口")
        
        # 构建基础查询
        query = select(ModelCallLog)
        
        # 应用过滤条件
        if start_date:
            try:
                start_datetime = datetime.strptime(start_date, "%Y-%m-%d")
                query = query.where(ModelCallLog.created_at >= start_datetime)
            except ValueError:
                raise HTTPException(status_code=400, detail="开始日期格式无效，应为YYYY-MM-DD")
                
        if end_date:
            try:
                # 将结束日期设置为当天的23:59:59
                end_datetime = datetime.strptime(end_date, "%Y-%m-%d")
                end_datetime = end_datetime.replace(hour=23, minute=59, second=59)
                query = query.where(ModelCallLog.created_at <= end_datetime)
            except ValueError:
                raise HTTPException(status_code=400, detail="结束日期格式无效，应为YYYY-MM-DD")
                
        if model_name:
            query = query.where(ModelCallLog.model_name == model_name)
            
        if user_id:
            query = query.where(ModelCallLog.user_id == user_id)
            
  
        
        # 计算总记录数
        count_query = select(func.count()).select_from(query.subquery())
        total_count = await session.execute(count_query)
        total_count = total_count.scalar() or 0
        
        # 应用分页
        query = query.order_by(ModelCallLog.created_at.desc())
        query = query.offset((page - 1) * page_size).limit(page_size)
        
        # 执行查询
        result = await session.execute(query)
        logs = result.scalars().all()
        
      
        
        # 获取可用的模型名称列表（用于前端过滤）
        model_names_query = select(ModelCallLog.model_name).distinct()
        model_names_result = await session.execute(model_names_query)
        model_names = [row[0] for row in model_names_result.all() if row[0]]
        
      
        # 计算统计信息
        stats = {
            "total_calls": total_count,
            "total_tokens": 0,
            "avg_tokens_per_call": 0,
            "avg_duration_ms": 0
        }
        
        if total_count > 0:
            # 计算总token数
            tokens_query = select(func.sum(ModelCallLog.tokens_total))
            tokens_result = await session.execute(tokens_query)
            total_tokens = tokens_result.scalar() or 0
            stats["total_tokens"] = total_tokens
            
            # 计算平均token数
            stats["avg_tokens_per_call"] = round(total_tokens / total_count, 2)
            
            # 计算平均响应时间
            duration_query = select(func.avg(ModelCallLog.duration_ms))
            duration_result = await session.execute(duration_query)
            avg_duration = duration_result.scalar() or 0
            stats["avg_duration_ms"] = round(avg_duration, 2)
        
        return {
            "status": True,
            "data": logs,
            "total": total_count,
            "page": page,
            "page_size": page_size,
            "total_pages": (total_count + page_size - 1) // page_size,
            "model_names": model_names,
            "stats": stats
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取AI大模型调用记录失败: {str(e)}")
